package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.recyclerview.widget.GridLayoutManager;

import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityCarPublish3Binding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddCarAddressEntity3;
import com.sgb.kjwl.model.entity.user.AddCarEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.CommonPickerEntity3;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LeaseCarPublishEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.adapter.MultiDictAdapter4;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.TimeRangePopWindow4;
import com.sgb.kjwl.viewmodel.self.publish.CarPublishModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

/**
 * 车辆发布步骤3
 */
public class CarPublishActivity3 extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private Thread thread;
    private ActivityCarPublish3Binding binding;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int MSG_LOAD_DATA_BACK = 0x0004;
    private static final int MSG_LOAD_BACK_SUCCESS = 0x0005;
    @Inject
    CarPublishModel3 viewModel;

    private int storePosition;
    private List<CommonPickerEntity3> storeEntityList;
    //    private Calendar pickUpDate;
//    private Calendar returnDate;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> pickupEntityList;
    private List<List<AddressEntity<List<AddressEntity>>>> pickupOpt2;
    private List<List<List<AddressEntity>>> pickupOpt3;
    private int pickupCityPosition1;
    private int pickupCityPosition2;
    private int pickupCityPosition3;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> backEntityList;
    private List<List<AddressEntity<List<AddressEntity>>>> backOpt2;
    private List<List<List<AddressEntity>>> backOpt3;
    private int backCityPosition1;
    private int backCityPosition2;
    private int backCityPosition3;
    private boolean isLoaded = false;
    private boolean backLoad = false;
    private List<ServiceEntity> serviceEntities;
    private AddCarEntity3 addCarEntity3 = new AddCarEntity3();
    private MapLongAndLatEntity pickupLongLat;
    private MapLongAndLatEntity returnLongLat;

    private MultiDictAdapter4 dictAdapter;
    private List<String> additionIds;
    private boolean isApprove = false;//是否需要审批

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, CarPublishActivity3.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        setTileImmerse(true);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(CarPublishActivity3.this, R.layout.activity_car_publish3);
        binding.setViewModel(viewModel);
        binding.topLayout.titleView.setText("车辆出租发布 3/3");
        binding.topLayout.ivBack.setOnClickListener(this);
        binding.topLayout.rightView.setText("暂存");
        binding.topLayout.rightView.setVisibility(View.VISIBLE);
        binding.topLayout.rightView.setOnClickListener(this);
        binding.preView.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvServicer.setOnWholeItemClickListener(this);
        binding.itemTvAllowTime.setOnWholeItemClickListener(this);
        binding.itemTvGetcararea.setOnWholeItemClickListener(this);
        binding.itemTvBackcararea.setOnWholeItemClickListener(this);
        binding.itemTvGetcaraddress.setOnWholeItemClickListener(this);
        binding.itemTvBackcaraddress.setOnWholeItemClickListener(this);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_PHONE);

        dictAdapter = new MultiDictAdapter4(CarPublishActivity3.this, null);
        binding.rlvList.setLayoutManager(new GridLayoutManager(CarPublishActivity3.this, 4));
        binding.rlvList.setAdapter(dictAdapter);
        dictAdapter.setMultiSelect(true);
        dictAdapter.setOnItemMultiClick(new BaseRecycleAdapter.OnItemMultiClick<DictEntity3>() {
            @Override
            public void onItemMultiClick(List<DictEntity3> dictEntity3s, int position) {
                additionIds.clear();
                for (DictEntity3 dictEntity3 : dictEntity3s) {
                    additionIds.add(dictEntity3.getId());
                }
                viewModel.addCarEntity.get().getAddCarStoreEntity3().setAdditionType(additionIds);
            }
        });

    }

    @Override
    protected void init() {
//        pickUpDate = Calendar.getInstance();
//        returnDate = Calendar.getInstance();
        pickupOpt2 = new ArrayList<>();
        pickupOpt3 = new ArrayList<>();
        backOpt2 = new ArrayList<>();
        backOpt3 = new ArrayList<>();
        additionIds = new ArrayList<>();
        viewModel.getCarAddition();
    }

    public void getCustomerOrgDataS(List<ServiceEntity> serviceEntities) {
        this.serviceEntities = serviceEntities;
        if (null != serviceEntities && serviceEntities.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(CarPublishActivity3.this, (options1, options2, options3, v) -> {
                String content = this.serviceEntities.get(options1).getName();
                binding.itemTvServicer.setContent(content);
                Objects.requireNonNull(viewModel.addCarEntity.get()).setContactsVo(this.serviceEntities.get(options1));
            }).build();
            businessOption.setPicker(this.serviceEntities);
            businessOption.setSelectOptions(0);
            businessOption.show();
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
//            case R.id.item_tv_store://选择类型个人/门店
//                if (storeEntityList != null) {
//                    showStorePicker(storeEntityList);
//                } else {
//                    viewModel.getPickerCarStore(false);
//                }
//                break;
//            case R.id.item_tv_getcartime://TODO
//                showPickupTimePop();
//                break;
//            case R.id.item_tv_backcartime:
//                showReturnTimePop();
//                break;
            case R.id.item_tv_allow_time://选择时间
                TimeRangePopWindow4 timeRangePopWindow4 = new TimeRangePopWindow4(getActivity());
                timeRangePopWindow4.setOnTimeCallBack(new TimeRangePopWindow4.OnTimeCallBack() {

                    @Override
                    public void result(long startTime, long endTime, String content) {
                        if (startTime < endTime) {
                            binding.itemTvAllowTime.setContent(content);
                            viewModel.addCarEntity.get().getAddCarStoreEntity3().setPickupAndReturnTime(Arrays.asList(String.valueOf(startTime), String.valueOf(endTime)));
                            timeRangePopWindow4.dismiss();
                        } else {
                            MToast.showToast(CarPublishActivity3.this, "结束时间不能小于开始时间");
                        }

                    }
                });
                timeRangePopWindow4.showAtLocation(binding.mainLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                timeRangePopWindow4.setTitle("取还车时间");
                break;
            case R.id.item_tv_getcararea://选择取车地区
                if (pickupEntityList != null) {
                    showpickupAreaPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
            case R.id.item_tv_backcararea://选择还车地区
                if (backEntityList != null) {
                    showBackAreaPop();
                } else {
                    viewModel.getBackAreaModel();
                }
                break;
            case R.id.item_tv_getcaraddress://选择取车地址
                if (pickupLongLat == null) {
                    MToast.showToast(CarPublishActivity3.this, "请先选择取车地区");
                    return;
                }

                getLocationLL(pickupLongLat, 251);
                //MapPositionActivity3.start(CarPublishActivity3.this, Double.parseDouble(pickupLongLat.getLng()), Double.parseDouble(pickupLongLat.getLat()), MapPositionActivity3.PICKUP_ADDRESS);
                break;
            case R.id.item_tv_backcaraddress:////选择还车地址
                if (returnLongLat == null) {
                    MToast.showToast(CarPublishActivity3.this, "请先选择还车地区");
                    return;
                }
                getLocationLL(returnLongLat, 252);
                //MapPositionActivity3.start(CarPublishActivity3.this, Double.parseDouble(returnLongLat.getLng()), Double.parseDouble(returnLongLat.getLat()), MapPositionActivity3.RETURN_ADDRESS);
                break;
            case R.id.item_tv_servicer://选择客服
                if (this.serviceEntities != null) {
                    getCustomerOrgDataS(serviceEntities);
                } else {
                    viewModel.getCustomerOrgDatas();
                }
                break;
        }
    }

    //  返回经纬度信息
    public void getLocationLL(MapLongAndLatEntity data, int requestCode) {
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, requestCode);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == 251) {//取车详细地址
            double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
            AddCarAddressEntity3 addCarAddressEntity3 = new AddCarAddressEntity3();
            addCarAddressEntity3.setLatitude(lat + "");
            addCarAddressEntity3.setLongitude(lon + "");
            addCarAddressEntity3.setAddressName(address);
            binding.itemTvGetcaraddress.setContent(address);
            viewModel.addCarEntity.get().getAddCarStoreEntity3().setPickupAddressEntity3(addCarAddressEntity3);
        } else if (requestCode == 252) {//还车详细地址
            double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
            AddCarAddressEntity3 addCarAddressEntity3 = new AddCarAddressEntity3();
            addCarAddressEntity3.setLatitude(lat + "");
            addCarAddressEntity3.setLongitude(lon + "");
            addCarAddressEntity3.setAddressName(address);
            binding.itemTvBackcaraddress.setContent(address);
            viewModel.addCarEntity.get().getAddCarStoreEntity3().setReturnAddressEntity3(addCarAddressEntity3);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA_BACK:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initBackJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showpickupAreaPop();
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_BACK_SUCCESS:
                    showBackAreaPop();
                    backLoad = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    public void showAdditionType(List<DictEntity3> dictEntityList) {
        dictAdapter.setDatas(dictEntityList);
        dictAdapter.checkDefultId(viewModel.addCarEntity.get().getAddCarStoreEntity3().getAdditionType());
    }

    public void showPickupAreraPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.pickupEntityList = datas;
        if (isLoaded) {
            showpickupAreaPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    public void showpickupAreaPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(CarPublishActivity3.this, (options1, options2, options3, v) -> {
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaName().clear();
            String areaName;
            if (pickupOpt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = pickupOpt3.get(options1).get(options2).get(options3).getName();
                pickupCityPosition3 = options3;
                Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaEntity3().setDistrictName(areaName);
                Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaEntity3().setDistrictNo(pickupOpt3.get(options1).get(options2).get(options3).getNo());

                Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaName().add(areaName);
            }
            String content = pickupEntityList.get(options1).getName()
                    + pickupOpt2.get(options1).get(options2).getName()
                    + areaName;
            pickupCityPosition1 = options1;
            pickupCityPosition2 = options2;
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaEntity3().setProvinceName(pickupEntityList.get(options1).getName());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaEntity3().setProvinceNo(pickupEntityList.get(options1).getNo());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaEntity3().setCityName(pickupOpt2.get(options1).get(options2).getName());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaEntity3().setCityNo(pickupOpt2.get(options1).get(options2).getNo());

            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaName().add(pickupEntityList.get(options1).getName());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getPickupAreaName().add(pickupOpt2.get(options1).get(options2).getName());

            binding.itemTvGetcararea.setContent(content);

            viewModel.getPickupLocationModel(pickupEntityList.get(options1).getNo(), pickupOpt2.get(options1).get(options2).getNo(), pickupOpt3.get(options1).get(options2).get(options3).getNo());
        }).build();
        cityOption.setPicker(pickupEntityList, pickupOpt2, pickupOpt3);
        cityOption.setSelectOptions(pickupCityPosition1, pickupCityPosition2, pickupCityPosition3);
        cityOption.show();
    }

    public void showBackAreraPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.backEntityList = datas;
        if (backLoad) {
            showBackAreaPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA_BACK);
        }
    }

    public void showBackAreaPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(CarPublishActivity3.this, (options1, options2, options3, v) -> {
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnupAreaName().clear();
            String areaName;
            if (backOpt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = backOpt3.get(options1).get(options2).get(options3).getName();
                backCityPosition3 = options3;
                Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnAreaEntity3().setDistrictName(areaName);
                Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnAreaEntity3().setDistrictNo(backOpt3.get(options1).get(options2).get(options3).getNo());

                Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnupAreaName().add(areaName);
            }
            String content = backEntityList.get(options1).getName()
                    + backOpt2.get(options1).get(options2).getName()
                    + areaName;
            backCityPosition1 = options1;
            backCityPosition2 = options2;
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnAreaEntity3().setProvinceName(backEntityList.get(options1).getName());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnAreaEntity3().setProvinceNo(backEntityList.get(options1).getNo());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnAreaEntity3().setCityName(backOpt2.get(options1).get(options2).getName());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnAreaEntity3().setCityNo(backOpt2.get(options1).get(options2).getNo());

            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnupAreaName().add(backEntityList.get(options1).getName());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarStoreEntity3().getReturnupAreaName().add(backOpt2.get(options1).get(options2).getName());

            binding.itemTvBackcararea.setContent(content);

            viewModel.getReturLnocationModel(backEntityList.get(options1).getNo(), backOpt2.get(options1).get(options2).getNo(), backOpt3.get(options1).get(options2).get(options3).getNo());
        }).build();
        cityOption.setPicker(backEntityList, backOpt2, backOpt3);
        cityOption.setSelectOptions(backCityPosition1, backCityPosition2, backCityPosition3);
        cityOption.show();
    }

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < pickupEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (addCarEntity3 != null && addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getProvinceName() != null && addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getProvinceName().equals(pickupEntityList.get(x).getName())) {
                pickupCityPosition1 = x;
            }
            pickupOpt2.add(pickupEntityList.get(x).getChildren());
            for (int i = 0; i < pickupEntityList.get(x).getChildren().size(); i++) {
                cityList.add(pickupEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (pickupEntityList.get(x).getChildren().get(i).getChildren() == null
                        || pickupEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(pickupEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            pickupOpt3.add(areaList);
        }
        if (addCarEntity3 != null) {
            if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getCityName() != null)
                for (int x2 = 0; x2 < pickupOpt2.size(); x2++) {
                    if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getCityName().equals(pickupEntityList.get(pickupCityPosition1).getChildren().get(x2).getName())) {
                        pickupCityPosition2 = x2;
                        break;
                    }
                }
            if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getDistrictName() != null)
                for (int x3 = 0; x3 < pickupOpt3.size(); x3++) {
                    if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getDistrictName().equals(pickupEntityList.get(pickupCityPosition1).getChildren().get(pickupCityPosition2).getChildren().get(x3).getName())) {
                        pickupCityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    private void initBackJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < backEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (addCarEntity3 != null && addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getProvinceName() != null && addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getProvinceName().equals(backEntityList.get(x).getName())) {
                backCityPosition1 = x;
            }
            backOpt2.add(backEntityList.get(x).getChildren());
            for (int i = 0; i < backEntityList.get(x).getChildren().size(); i++) {
                cityList.add(backEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (backEntityList.get(x).getChildren().get(i).getChildren() == null
                        || backEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(backEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            backOpt3.add(areaList);
        }
        if (addCarEntity3 != null) {
            if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getCityName() != null)
                for (int x2 = 0; x2 < backOpt2.size(); x2++) {
                    if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getCityName().equals(backEntityList.get(backCityPosition1).getChildren().get(x2).getName())) {
                        backCityPosition2 = x2;
                        break;
                    }
                }
            if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getDistrictName() != null)
                for (int x3 = 0; x3 < backOpt3.size(); x3++) {
                    if (addCarEntity3.getAddCarStoreEntity3().getPickupAreaEntity3().getDistrictName().equals(backEntityList.get(backCityPosition1).getChildren().get(backCityPosition2).getChildren().get(x3).getName())) {
                        backCityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_BACK_SUCCESS);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.right_view:
                viewModel.addCarEntity.get().setState("0");//草稿
                validity();
                break;
            case R.id.next_view:
                viewModel.addCarEntity.get().setState("1");//默认上架
                validity();
                break;
            case R.id.pre_view:
            case R.id.iv_back:
                saveAddCarEntity();
                EventBus.getDefault().post(LeaseCarPublishEvent.make().setMessageTag(EventConstant.EVENT_CAR_LEAS_PUBLISH).setMessageData(viewModel.addCarEntity.get()));
                finish();
                break;
        }
    }

    private void validity() {
        if (TextUtils.isEmpty(binding.itemTvContact.getContent())) {
            MToast.showToast(CarPublishActivity3.this, "请输入联系人");
            return;
        }
        if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
            MToast.showToast(CarPublishActivity3.this, "请输入联系电话");
            return;
        }
        if (binding.itemTvName.getVisibility() == View.VISIBLE) {
            if (TextUtils.isEmpty(binding.itemTvName.getContent())) {
                MToast.showToast(CarPublishActivity3.this, "请输入门店名称");
                return;
            } else {
                viewModel.addCarEntity.get().getAddCarStoreEntity3().setContactStoreName(binding.itemTvName.getContent());
            }
        }
        if (TextUtils.isEmpty(binding.itemTvAllowTime.getContent())) {
            MToast.showToast(CarPublishActivity3.this, "请选择取还车时间");
            return;
        }
        if (TextUtils.isEmpty(binding.itemTvGetcararea.getContent())) {
            MToast.showToast(CarPublishActivity3.this, "请选择取车地区");
            return;
        }
        if (TextUtils.isEmpty(binding.itemTvGetcaraddress.getContent())) {
            MToast.showToast(CarPublishActivity3.this, "请选择详细地址");
            return;
        }

//        if (TextUtils.isEmpty(binding.itemTvBackcararea.getContent())) {
//            MToast.showToast(CarPublishActivity3.this, "请选择还车地区");
//            return;
//        }
//        if (TextUtils.isEmpty(binding.itemTvBackcaraddress.getContent())) {
//            MToast.showToast(CarPublishActivity3.this, "请选择详细地址");
//            return;
//        }
        //企业用户判断是否需要审批
        if (viewModel.addCarEntity.get().isCompany()&& !"0".equals(viewModel.addCarEntity.get().getState())) {
            viewModel.haveApprovalOrNot(viewModel.addCarEntity.get().getMyCompanyNo(),"carRelease");
        } else {
            viewModel.publishModel();
            binding.nextView.setEnabled(false);
        }
    }

//    public void showChooseStorePicker(List<CommonPickerEntity3> storeEntityList) {
//        if (storeEntityList == null || storeEntityList.size() == 0) {
//            return;
//        }
//        binding.itemTvStore.setContent(storeEntityList.get(0).getName());
//        if ("0".equals(storeEntityList.get(0).getId())) {
//            binding.itemTvName.setVisibility(View.VISIBLE);
//        } else {
//            binding.itemTvName.setVisibility(View.GONE);
//        }
//
//        Objects.requireNonNull(viewModel.addCarEntity.get()).setContactStoreType(storeEntityList.get(0).getId());
//        Objects.requireNonNull(viewModel.addCarEntity.get()).setContactStoreTypeLabel(storeEntityList.get(0).getName());
//    }
//
//    public void showStorePicker(List<CommonPickerEntity3> storeEntityList) {
//        this.storeEntityList = storeEntityList;
//        OptionsPickerView businessOption = new OptionsPickerBuilder(CarPublishActivity3.this, (options1, options2, options3, v) -> {
//            if (storeEntityList == null || storeEntityList.size() == 0) {
//                return;
//            }
//            if ("0".equals(storeEntityList.get(options1).getId())) {
//                binding.itemTvName.setVisibility(View.VISIBLE);
//            } else {
//                binding.itemTvName.setVisibility(View.GONE);
//            }
//            String content = storeEntityList.get(options1).getName();
//            binding.itemTvStore.setContent(content);
//            storePosition = options1;
//            Objects.requireNonNull(viewModel.addCarEntity.get()).setContactStoreType(storeEntityList.get(options1).getId());
//            Objects.requireNonNull(viewModel.addCarEntity.get()).setContactStoreTypeLabel(content);
//        }).build();
//        businessOption.setPicker(storeEntityList);
//        businessOption.setSelectOptions(storePosition);
//        businessOption.show();
//    }

    public void showPickupLocation(MapLongAndLatEntity longLat) {
        this.pickupLongLat = longLat;
    }

    public void showReturnLocation(MapLongAndLatEntity longLat) {
        this.returnLongLat = longLat;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LeaseCarPublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CAR_CONTACT_PUBLISH) {
            AddCarEntity3 addCarEntity3 = (AddCarEntity3) event.getMessageData();
            viewModel.addCarEntity.set(addCarEntity3);
            showEdit();
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    private void showEdit() {
        //设置门店名称
        String myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (!TextUtils.isEmpty(myCompanyNo) && !"0".equals(myCompanyNo)) {
            binding.itemTvName.setVisibility(View.VISIBLE);
            if (viewModel.addCarEntity.get().getAddCarStoreEntity3() != null) {
                binding.itemTvName.setContent(viewModel.addCarEntity.get().getAddCarStoreEntity3().getContactStoreName());
            }
        } else {
            binding.itemTvName.setVisibility(View.GONE);
        }

        //取还车时间
        if (viewModel.addCarEntity.get().getAddCarStoreEntity3().getPickupAndReturnTime() != null
                && viewModel.addCarEntity.get().getAddCarStoreEntity3().getPickupAndReturnTime().size() > 0) {
            String pickTime = viewModel.addCarEntity.get().getAddCarStoreEntity3().getPickupAndReturnTime().get(0);
            String backTime = viewModel.addCarEntity.get().getAddCarStoreEntity3().getPickupAndReturnTime().get(1);
            binding.itemTvAllowTime.setContent(timeStamp2Date(pickTime, "HH:mm") + " - " + timeStamp2Date(backTime, "HH:mm"));
        }
        String pickupAddress = viewModel.addCarEntity.get().getAddCarStoreEntity3().getPickupAddressEntity3().getAddressName();
        binding.itemTvGetcaraddress.setContent(pickupAddress);
        String returnAddress = viewModel.addCarEntity.get().getAddCarStoreEntity3().getReturnAddressEntity3().getAddressName();
        binding.itemTvBackcaraddress.setContent(returnAddress);
        binding.itemTvGetcararea.setContent(viewModel.addCarEntity.get().getAddCarStoreEntity3().getPickupAreaEntity3().getAreaName());
        binding.itemTvBackcararea.setContent(viewModel.addCarEntity.get().getAddCarStoreEntity3().getReturnAreaEntity3().getAreaName());
    }

    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (seconds.equals("0")) {
            return "00:00";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }

    public void showReNext() {
        binding.nextView.setEnabled(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void saveAddCarEntity() {
        viewModel.addCarEntity.get().getAddCarStoreEntity3().setContactStoreName(binding.itemTvName.getContent());
    }

    /**
     * 0.暂存:保存成功
     * 1.需要审批:提交成功(发布前提示需要审批对话框)
     * 2.不需要审批:发布成功(发布前提示不需要审批对话框)
     */
    public void showSuccess() {
        if ("0".equals(viewModel.addCarEntity.get().getState())) {
            MToast.showToast(this, "保存成功");
        } else if (isApprove) {
            MToast.showToast(this, "提交成功");
        } else {
            MToast.showToast(this, "发布成功");
        }
    }

    /**
     * 提示审批对话框
     *
     * @param b
     */
    public void showPublishTip(boolean b) {
        isApprove = b;
        String msg = b ? "确认提交当前审批业务？" : "当前内容不需要审核，提交后即发布，确认提交？";
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("系统提示")
                .setMsg(msg)
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        viewModel.publishModel();
                        binding.nextView.setEnabled(false);
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }
}

